<!-- 累计流量 -->
<template>
  <px-dialog v-model="visible" width="80%" :title="title" @close="cancel">
    <div class="flex-center table-top">
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="时间粒度" prop="type">
          <px-select v-model="queryParams.type" placeholder="请选择时间粒度" @change="changeDateType">
            <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="queryParams.type === 'year'" label="时间范围" prop="date">
          <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
        </px-form-item>
        <px-form-item v-if="queryParams.type === 'months'" label="时间范围" prop="date">
          <px-date-picker
            v-model="queryParams.date"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="YYYY-MM-DD"
          />
        </px-form-item>
        <px-form-item v-if="queryParams.type === 'day'" label="时间范围" prop="date">
          <px-date-picker
            v-model="queryParams.date"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
        </div>
      </px-form>
    </div>
    <div v-loading="loading" class="content">
      <div v-if="haveData" ref="chartRef" class="chart-container" />
      <px-empty v-else description="暂无数据" />
    </div>
  </px-dialog>
</template>
<script setup>
import { ref, reactive, nextTick, toRefs, computed, onMounted } from "vue";
import * as echarts from "echarts";
import dayjs from "dayjs";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import { queryScadaIndicator } from "@/api/machineApi";
import { formatMissingData } from "@/utils/common";

const emits = defineEmits(["update:visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default() {
      return {};
    }
  }
});
const title = "累计流量" + "-" + props?.data?.gasName;

const chartRef = ref(null);

const state = reactive({
  loading: false,
  typeList: [
    {
      label: "年",
      value: "year"
    },
    {
      label: "月",
      value: "months"
    },
    {
      label: "日",
      value: "day"
    }
  ],
  queryParams: {
    type: "day",
    date: ""
  },
  haveData: true
});

const { loading, typeList, queryParams, haveData } = toRefs(state);

const dateValue = ref({ startYear: new Date().getFullYear() - 2, endYear: new Date().getFullYear() });

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const changeDateType = val => {
  if (val === "year") {
    state.queryParams.date = [`${new Date().getFullYear() - 2}`, `${new Date().getFullYear()}`];
  }
};

const updateStatisticYear = (startYear, endYear) => {
  state.queryParams.date = [`${startYear}`, `${endYear}`];
};

const cancel = () => {
  emits("update:visible", false);
};

const indicator = "SUM";

const getBarData = async () => {
  try {
    state.loading = true;
    let startTime = "";
    let endTime = "";
    if (state.queryParams.type === "year") {
      startTime = state.queryParams.date
        ? `${state.queryParams.date[0]}-01-01 00:00:00`
        : dayjs().subtract(2, "year").format("YYYY") + `-01-01 00:00:00`;
      endTime = state.queryParams.date ? `${state.queryParams.date[1]}-12-31 23:59:59` : dayjs().format("YYYY") + `-12-31 23:59:59`;
    } else {
      startTime = state.queryParams.date ? `${state.queryParams.date[0]} 00:00:00` : dayjs().subtract(7, "day").format("YYYY-MM-DD") + ` 00:00:00`;
      endTime = state.queryParams.date ? `${state.queryParams.date[1]} 23:59:59` : dayjs().subtract(1, "day").format("YYYY-MM-DD") + ` 23:59:59`;
    }
    let point = [`${props.data?.currentPoint?.replace(/_01|_PV/g, "")}_01_Total_CALCULATE`];
    const res = await queryScadaIndicator({
      contentType: "LIST",
      bucketWidth: 1,
      bucketUnit: state.queryParams.type,
      point,
      scale: "0.2",
      // indicators: ["LAST"],
      indicators: [indicator],
      startTime: startTime,
      endTime: endTime,
      pageNum: 0,
      pageSize: 0
    });
    if (res && res.rows && res.rows?.length) {
      state.haveData = true;
      drawChart(res, chartRef.value);
    } else {
      state.haveData = false;
    }
  } catch (error) {
    console.log(error);
    state.haveData = false;
  } finally {
    state.loading = false;
  }
};
// 柱状图
const drawChart = (data, dom) => {
  let type = state.queryParams.type;
  let myChart = echarts.init(dom);
  let xAxisData = data?.rows?.map(i => {
    let flag = i[type]?.split(" ")[0];
    let arr = flag?.split("-");
    if (type === "year") {
      return arr[0];
    } else if (type === "months") {
      return arr[0] + "-" + arr[1];
    } else if (type === "day") {
      return flag;
    }
  });
  const min = value => {
    if (value.min < 0) {
      return Math.round(value.min * 1.5);
    } else {
      return 0;
    }
  };
  const max = value => {
    return Math.round(value.max * 1.5);
  };
  const seriesData = formatMissingData(data.rows.map(v => v[`${indicator.toLowerCase()}_value`]));
  let option = {
    grid: {
      left: 100,
      right: 50,
      top: 50,
      bottom: 70
    },
    tooltip: {
      // axisPointer: {
      //   type: "shadow"
      // },
      trigger: "axis",
      formatter: params => {
        // const { name, value } = params;
        // return `${name}：${value?.toFixed(2)}`;
        const { name, value } = params[0];
        return `${name}：${value?.toFixed(2)}`;
      }
    },

    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      show: true,
      type: "category",
      data: xAxisData
      // axisLabel: {
      //   interval: 0,
      //   rotate: 45
      // }
    },
    yAxis: {
      show: true,
      type: "value",
      name: "",
      min,
      max,
      axisLine: {
        show: true, // 显示 Y 轴轴线
        lineStyle: {
          width: 1, // 轴线宽度
          type: "solid" // 轴线样式，可选值：'solid'（实线）、'dashed'（虚线）、'dotted'（点线）
        }
      }
    },
    dataZoom: [
      {
        type: "slider",
        orient: "vertical",
        filterMode: "none",
        left: 0,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "vertical",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "slider",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      },
      {
        type: "inside",
        orient: "horizontal",
        filterMode: "none",
        start: 0,
        end: 100
      }
    ],
    series: [
      {
        // data: formatMissingData(data.rows.map(v => v.last_value)),
        data: seriesData,
        type: "bar"
      },
      {
        // data: formatMissingData(data.rows.map(v => v.last_value)),
        data: seriesData,
        type: "line"
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

// 查询
const handleQuery = () => {
  getBarData();
};
handleQuery();
</script>
<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.px-form-item {
  width: auto;
}

.content {
  display: flex;
  align-items: center;
  justify-content: center;
  // width: 1000px;
  width: 100%;
  height: 550px;

  .chart-container {
    width: 100%;
    height: 100%;
  }
}

// .associate-content {
//   display: flex;
//   flex-wrap: wrap;
//   width: 1000px;
//   height: 500px;
// }

// .associate-container {
//   width: 480px;
//   height: 200px;
//   margin: 0 16px 16px 0;
//   border: 1px solid rgb(24 24 24 / 15%);
// }

// .associate-chart-container {
//   width: 100%;
//   height: 100%;
// }
</style>
